#include "CActionEllipse.h"

static inline float ellipseXat( float a, float bx, float b, float t )
{
	return a*cos(2*PI*t)+bx;
}
static inline float ellipseYat( float a, float by, float b, float t )
{
	return b*sin(2*PI*t)+by;
}

CActionEllipse* CActionEllipse::create(float duration, ActionEllipseConfig c)
{
	CActionEllipse *pActionEllipse = new CActionEllipse();
	pActionEllipse->initWithDuration(duration, c);
	pActionEllipse->autorelease();

	return pActionEllipse;
}

CActionEllipse* CActionEllipse::actionWithDuration(float duration, ActionEllipseConfig c)
{
	return CActionEllipse::create(duration, c);
}

bool CActionEllipse::initWithDuration(float duration, ActionEllipseConfig c)
{
	if (CCActionInterval::initWithDuration(duration))
	{
		m_sConfig = c;
		return true;
	}

	return false;
}

CCObject* CActionEllipse::copyWithZone(CCZone *pZone)
{
	CCZone* pNewZone = NULL;
	CActionEllipse* pCopy = NULL;
	if(pZone && pZone->m_pCopyObject) 
	{
		pCopy = (CActionEllipse*)(pZone->m_pCopyObject);
	}
	else
	{
		pCopy = new CActionEllipse();
		pZone = pNewZone = new CCZone(pCopy);
	}

	CCActionInterval::copyWithZone(pZone);

	pCopy->initWithDuration(m_fDuration, m_sConfig);

	CC_SAFE_DELETE(pNewZone);
	return pCopy;
}

void CActionEllipse::startWithTarget(CCNode *pTarget)
{
	CCActionInterval::startWithTarget(pTarget);
}

void CActionEllipse::update(float time)
{
	if (m_pTarget)
	{
		CCPoint s_startPosition =m_sConfig.centerPosition;
		float a = m_sConfig.aLength;
		float b = m_sConfig.bLength;
		float bx = m_sConfig.centerPosition.x;
		float by = m_sConfig.centerPosition.y;
		float x = ellipseXat(a, bx, b, time);
		float y = ellipseYat(a, by, b, time);
		CCPoint p = ccp(x, y);
		m_pTarget->setPosition(p);
	}
}
